package lc20240525;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

//合并区间
public class MergeSection {
    public static void main(String[] args) {
        int[][] array = {
                {1,3},
                {2,6},
                {8,10},
                {15,18}
        };
        System.out.println(Arrays.deepToString(merge(array)));
    }

    public static int[][] merge(int[][] intervals) {
        //排序
        Arrays.sort(intervals, (o1, o2) -> o1[0] - o2[0]);

        List<int[]> list = new ArrayList<>();
        int[] curInt = intervals[0];
        list.add(curInt);
        //之所以会修改list，是因为curInt是引用类型，内容变化，list里面的值也随之变化。
        for (int[] ints : intervals) {
            int curEnd = curInt[1];
            int nextStart = ints[0];
            int nextEnd = ints[1];
            if (curEnd >= nextStart) {
                curInt[1] = Math.max(nextEnd, curEnd);
            } else {
                list.add(ints);
                curInt = ints;
            }
        }
        return list.toArray(new int[list.size()][]);
    }
}
